#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>

void timer_handler(union sigval arg)
{
  printf("Sent message: %s\n", (char *) arg.sival_ptr);
}

int main(int argc, char *argv[])
{
  timer_t            timerid;
  long long          freq_nanosecs;
  struct sigevent    sev;
  struct itimerspec  its;

  if (argc != 3) {
    fprintf(stderr, "Usage: %s <sleep-secs> <freq-nanosecs>\n",
           argv[0]);
    exit(EXIT_FAILURE);
  }

  /* Create the timer. */

  char *test = "hello";
  sev.sigev_notify_function = timer_handler;
  sev.sigev_notify = SIGEV_THREAD;
  sev.sigev_value.sival_ptr = test;
  sev.sigev_notify_attributes = NULL;
  if (timer_create(CLOCK_REALTIME, &sev, &timerid) == -1) {
    perror("timer create"); exit(EXIT_FAILURE);
  }
  printf("timer ID is %#jx\n", (uintmax_t) timerid);

  /* Start the timer. */

  freq_nanosecs = atoll(argv[2]);
  its.it_value.tv_sec = freq_nanosecs / 1000000000;
  its.it_value.tv_nsec = freq_nanosecs % 1000000000;
  its.it_interval.tv_sec = its.it_value.tv_sec;
  its.it_interval.tv_nsec = its.it_value.tv_nsec;
  if (timer_settime(timerid, 0, &its, NULL) == -1) {
   perror("timer settime"); exit(EXIT_FAILURE);
  }

  /* Sleep for a while; meanwhile, the timer may expire
    multiple times. */
  printf("Sleeping for %d seconds\n", atoi(argv[1]));
  sleep(atoi(argv[1]));

  exit(EXIT_SUCCESS);
}

